package cn.klaw.config;

import com.baomidou.lock.aop.LockAnnotationAdvisor;
import com.baomidou.lock.aop.LockInterceptor;
import org.springframework.aop.Pointcut;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

/**
 * Lock4jAop开关
 */
@Configuration(proxyBeanMethods = false)
public class Lock4jAutoConfiguration {

    @Bean
    @ConditionalOnProperty(prefix = "lock4j.aop", name = "enabled", havingValue = "true", matchIfMissing = false)
    public LockAnnotationAdvisor lockAnnotationAdvisor(LockInterceptor lockInterceptor) {
        return new LockAnnotationAdvisor(lockInterceptor, Ordered.HIGHEST_PRECEDENCE){
            private final AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();

            {
                pointcut.setExpression("within(cn.klaw..*) && @annotation(com.baomidou.lock.annotation.Lock4j)");
            }

            @Override
            public Pointcut getPointcut() {
                return pointcut;
            }
        };
    }

    @Bean
    @ConditionalOnProperty(prefix = "lock4j.aop", name = "enabled", havingValue = "false", matchIfMissing = true)
    public LockAnnotationAdvisor lockAnnotationAdvisor2(LockInterceptor lockInterceptor) {
        return new LockAnnotationAdvisor(lockInterceptor, Integer.MIN_VALUE) {
            private final AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();

            {
                this.pointcut.setExpression("within(cn.klaw.config.*) && @annotation(com.baomidou.lock.annotation.Lock4j)");
            }

            public Pointcut getPointcut() {
                return this.pointcut;
            }
        };
    }
}
